﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VB.Common.Extensions
{
    public static class StringExtentions
    {
        private static List<String> NonBreakableWords = null;

        public static void SetNonBreakableWords(List<String> words)
        {
            NonBreakableWords = words;
        }       

        /// <summary>
        /// Define if spesified symbol is a white space
        /// </summary>
        /// <param name="source"></param>
        /// <param name="index">Sybol index starting from 0</param>
        /// <returns></returns>
        public static Boolean IfSybolIsWhileSpace(this String source, Int32 index)
        {
            return String.IsNullOrWhiteSpace(source[index].ToString());
        }

        /// <summary>
        /// Trim resource string to an appopriate lenght taking into account words breaking.
        /// </summary>
        /// <param name="source">Input string</param>
        /// <param name="length">Length of the output string</param>
        /// <returns></returns>
        public static String TrimLiteral(this String source, Int32 length)
        {
            if (NonBreakableWords == null) throw new TypeLoadException("Non Breakable Words must be set before TrimLiteral van be used");
            if (length <= 0) throw new ArgumentOutOfRangeException("Trim length must be greater than 0");
            if (length > source.Trim().Length) throw new ArgumentOutOfRangeException("Trim length must be less than source length.");

            String result = source.Trim();
                        
            //Define if the last Symbol is space. Add sybols until it is space or end of the source
            Boolean lastWordIsNotBreakable = true;
            Int32 lastSymbol = length - 1;
            while (lastWordIsNotBreakable)
            {                
                while (((lastSymbol + 1) != result.Length) && !result.IfSybolIsWhileSpace(lastSymbol))
                {
                    lastSymbol++;
                }

                if (result.IfSybolIsWhileSpace(lastSymbol)) lastSymbol--;

                String lastWord = result.Substring(0, lastSymbol + 1).Split(' ').Last();
                lastWordIsNotBreakable = NonBreakableWords.Exists(w => w == lastWord);
                if (lastWordIsNotBreakable) lastSymbol += 2;
            }


            //Define if the last WORD is non breakable  sybols. Add words until it is non reakable or end of the source

            return result.Substring(0, lastSymbol + 1);
        }      
    }
}
